<?php
namespace Api\Controller;

class CashController extends WXController
{	
    public $tbName = CONTROLLER_NAME;
    /*待验证的参数*/
    public $tca = [
        'user_id' => [
            'method' => 'exists',
            'model' => 'member',
            'code_key' => 'lawless'
        ],
        'money' => [
            'method' => 'regex',
            'model' => '/^[1-9]\d*$/',
            'code_key' => 'money_error'
        ]
    ];
    /*保存参数*/
    public $field = ['user_id','money'];
    /**
     * 申请提现
     */
    public function index() {
        try{
            $this->safeChecked();
            /*验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $data = I('param.');
            $Cash = M($this->tbName);
            $user_id = $data['user_id'];
            //获取审核中或已提现的佣金
            $cash_total = $Cash->where(array('user_id' => $user_id,'status' => array('IN',[1,2])))->sum('money')?:0;
            $Commission = M('commisson');
            //获取可提现佣金   总佣金 - 审核中的佣金 - 已提现的佣金
            $commission_total = $Commission->where(array('user_id' => $user_id))->sum('money')?:0;
            $valid_total = $commission_total - $cash_total;
            if($data['money'] > $valid_total){
                $this->res_data['code_key'] = 'asset_not_enough';
                $this->apiReply();
            }
            //数据保存
            $param = $data;
            $this->filterCoupon($data);
            $data['crdate'] = $data['tstamp'] = time();
            $id = $Cash->add($data);
            if(!$id){
                debug($Cash->_sql());
                $this->res_data['code_key'] = 'fail';
            }
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 微信支付->商户对用户
     * @param   string  appid
     * @param   string  mchid
     * @param   string  key
     * @param   string  transaction_id   微信支付单号
     * @param   string  pay_price        订单金额
     */
    public function wxpay(){
        try{
            $obj = D('Base');
            /*数据整理请求接口*/
            $params = array(
                'mch_appid' => 'wxa21a7f6aa2118016 ',
                'mchid' => '1523859041',
                'nonce_str' => $obj->CreateInviteCode(),
                'partner_trade_no' => date('YmdHis'),
                'openid' => 'owEdd5UbEZXrL4vUTTXE1anCCESw',
                'check_name' => 'NO_CHECK',
                'amount' => 100,
                'desc' => '提现',
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR']
            );
            //证书
            $path = $_SERVER['DOCUMENT_ROOT'].'/'.C('CERT');
            //文件名
            $cert = 'apiclient_cert.pem';
            $key = 'apiclient_key.pem';
            $cert = $path . $cert;
            $key = $path . $key;
            //获取保存文件的物理路径
            $params = $this->getSignParams($params);
            $params = $this->createLinkString($params,'pinhaocai31001523211050042805mlw');
            $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
            $res = $this->curlPostSLL($url,$params,$key,$cert);
            debug($res);
            if(!$res){
                $this->ajaxReturn($result);
                $this->error('证书错误,请重新上传证书',U(CONTROLLER_NAME.'/index?type=1'));
            }
            /*返回结果验证*/
            $res = (array)simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
            debug($res);
            p($res);
        }catch(\Exception $e){
            p($e);
            debug($e->getmessage());
            $this->error('操作失败',U(CONTROLLER_NAME.'/index?type=1'));
        }
    }

    //使用证书
    public function curlPostSLL($url,$data,$key,$cert){
        //初始化curl句柄，
        $ch = curl_init();
        /*设置不使用CA证书*/
        $opt[CURLOPT_SSL_VERIFYHOST] = 2;
        $opt[CURLOPT_SSL_VERIFYPEER] = FALSE;
        curl_setopt_array($ch, $opt);
        //设置服务器返回的数据不直接输出，而是保留在curl_exec()的返回值中
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        /**--------微信退款证书---------**/
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,$cert);
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,$key);
        /**--------微信退款证书---------**/

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,true);
        $xml = '<xml>';
        foreach($data as $k => $val){
            $xml .= '<'.$k.'>'.$val.'</'.$k.'>';
        }
        $xml .= '</xml>';
        $data = $xml;
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

	 /*数据筛选*/
    public function filterCoupon(&$data){
        foreach ($data as $key => $value) {
            if(!in_array($key,$this->field)){
                unset($data[$key]);
            }
        }
    }
}